import { type UseQueryResult, useQuery } from "@tanstack/react-query";
import { RefreshCwIcon } from "lucide-react";
import { getJoke } from "@/apis/joke";
import Button from "@/components/Button";
import Panel from "@/components/Panel";

export default function JokePage() {
  const query = useQuery({
    queryKey: ["joke"],
    queryFn: async () => {
      const resp = await getJoke();
      if (resp.error) {
        throw new Error("Get joke failed");
      }
      return resp.joke;
    },
  });

  return (
    <div className="max-w-md mx-auto mt-36">
      <Panel
        titleClassName="justify-between"
        title={
          <>
            Joke
            <Button size="sm" shape="circle" onClick={() => query.refetch()}>
              <RefreshCwIcon />
            </Button>
          </>
        }
      >
        <QueriedJoke {...query} />
      </Panel>
      <div className="mt-6 flex justify-end">
        <a href="https://jokeapi.dev/" target="__blank">
          About jokeapi.
        </a>
      </div>
    </div>
  );
}

function QueriedJoke({ status, fetchStatus, data, error }: UseQueryResult<string, Error>) {
  if (status === "pending" || fetchStatus === "fetching") {
    return <div>Loading...</div>;
  }

  if (status === "error") {
    return <div>Error: {error.message}</div>;
  }

  return <div>{data}</div>;
}
